package de.au.fi.controller;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import de.au.fi.calc.CalcHelper;
import de.au.fi.calc.results.ResultFactory;
import de.au.fi.domain.Stock;
import de.au.fi.manager.StockManager;


@Component
@Scope("session")
public class StockController 
{
	Stock stock = new Stock();
	
	@Autowired
	StockManager stockManager;
	
	public String save()
	{
		this.stock = stockManager.save(stock);
		stock.setResult(ResultFactory.getResult(stock));
		return null;
	}

	public void setStockIfPresent(AjaxBehaviorEvent ajaxBehaviorEvent )
	{
		HtmlInputText inputText =  (HtmlInputText) ajaxBehaviorEvent.getSource();
		String submittedVal = inputText.getValue().toString();
		if(stockManager.contains(submittedVal))
		{
			this.stock = stockManager.get(submittedVal);
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("stock found for wkn, stock loaded"));
			this.stock.setResult(ResultFactory.getResult(stock));
		}
		else
		{
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("no stock found for wkn, new stock created"));
			this.stock = new Stock();
			this.stock.setWkn(submittedVal);
		}
	}
	
	public String openStock()
	{
		stock = stockManager.get(this.stock.getWkn());
		return null;
	}
	
	public List<Stock> getCurrentStockAsList()
	{
		if(this.stock==null)return null;
		List<Stock> stocks = new ArrayList<Stock>();
		stocks.add(stock);
		return stocks;
	}

	public Stock getStock() {
		return stock;
	}

	public void setStock(Stock stock) {
		this.stock = stock;
	}
}
